import gameconn from 'gamerpc'
import { EventManager } from '../event/EventManager';
class GameRpc {
    public connector;
    public config = {
        UrlHead: "https",              //协议选择: http/https
        webserver: {
            "url": "index.gamegold.xin",//远程主机地址
            "host": "122.9.94.67",      //远程主机地址
            "port": 9901              //远程主机端口
        },
        logicserver: {},
        oemInfo: {                    //模拟用户信息
            domain: 'CoreOfKow',        //指定访问的逻辑服务器类型
            token: '',                  //用户令牌，由920客户端向920服务端索取并填充于此
            openid: '',
            auth: null,
        },
    }

    private NotifyType = {
        action: 1,          //体力数值推送
        chat: 2,             //聊天消息
        mail: 3,             //邮件
    };

    isLogin: Boolean = false;
  
    prefix: string = 'bxs.'

    getQuery() {
        let list = location.search.substring(1).split('&')
        let obj = { id: '' }
        for (let item of list) {
            let arr = item.split('=')
            obj[arr[0]] = arr[1]
        }
        return obj
    }

    setOpenid(openid) {

        if (openid.indexOf(this.prefix) != 0) {
            openid = this.prefix + openid
        }

        this.config.oemInfo.openid = openid
    }

    setToken(token) {

        this.config.oemInfo.token = token
    }

    public async login() {
        if (this.isLogin) {
            return
        }

        if(!this.config.oemInfo.openid){
            this.setOpenid(this.getQuery().id)
        }

        this.connector = new gameconn(this.config);

        //设置长连接模式，同时订阅特定消息
        this.connector.setmode(this.connector.CommMode.ws).watch(msg => {
            console.log('收到下行消息', msg);
            EventManager.instance.emit(EventManager.EventType.Notice, msg)
        }, this.NotifyType.chat);

        
        this.config.oemInfo.auth = {
            openid: this.config.oemInfo.openid,
            token: this.config.oemInfo.token,
          };
       
        //和索引服交互并最终登录逻辑服
        console.log(this.config.oemInfo)
        let res = await this.connector.login(this.config.oemInfo);
        console.log('login:',res)
        this.isLogin = true
        

    }


    public async fetching(params) {
        await this.login()
        return await this.connector.fetching(params);
    }

}


export default new GameRpc()


